package org.jin.jinaicode.service.impl;

import cn.hutool.core.io.FileUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jin.jinaicode.common.BaseResponse;
import org.jin.jinaicode.common.DeleteRequest;
import org.jin.jinaicode.common.ResultUtils;
import org.jin.jinaicode.core.AiCodeGeneratorFacade;
import org.jin.jinaicode.core.builder.VueProjectBuilder;
import org.jin.jinaicode.core.hanlder.StreamHandlerExecutor;
import org.jin.jinaicode.exception.BusinessException;
import org.jin.jinaicode.exception.ErrorCode;
import org.jin.jinaicode.exception.ThrowUtils;
import org.jin.jinaicode.mapper.AppMapper;
import org.jin.jinaicode.model.dto.user.AppAddDTO;
import org.jin.jinaicode.model.dto.user.AppQueryDTO;
import org.jin.jinaicode.model.dto.user.AppUpdateDTO;
import org.jin.jinaicode.model.dto.admin.AppQueryAdminDTO;
import org.jin.jinaicode.model.dto.admin.AppUpdateAdminDTO;
import org.jin.jinaicode.model.dto.admin.AppFeatureDTO;
import org.jin.jinaicode.model.dto.user.AppPublicDTO;
import org.jin.jinaicode.model.enums.ChatHistoryMessageTypeEnum;
import org.jin.jinaicode.model.enums.CodeGenTypeEnum;
import org.jin.jinaicode.model.entity.App;
import org.jin.jinaicode.model.entity.User;
import org.jin.jinaicode.model.vo.AppVO;
import org.jin.jinaicode.model.vo.UserBasicVO;
import org.jin.jinaicode.service.AppService;
import org.jin.jinaicode.service.ChatHistoryService;
import org.jin.jinaicode.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import org.jin.jinaicode.constant.UserConstant;
import org.jin.jinaicode.constant.AppConstant;
import reactor.core.publisher.Flux;

/**
 * 应用 服务层实现。
 * 
 * 改造说明：
 * 1. 新增 UserBasicVO 类，包含用户基础信息
 * 2. 改造 AppVO，添加 user 字段，包含创建用户的基础信息
 * 3. 优化查询性能，使用批量查询用户信息，避免 N+1 查询问题
 * 4. 所有获取应用详情的接口都会返回用户基础信息
 *
 * @author 小堇
 */
@Service
@Slf4j
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements AppService {

  @Resource
  private StreamHandlerExecutor streamHandlerExecutor;

  @Resource
  private AppMapper appMapper;

  @Resource
  private UserService userService;

  @Resource
  private AiCodeGeneratorFacade aiCodeGeneratorFacade;

  @Resource
  private ChatHistoryService chatHistoryService;

  @Resource
  private VueProjectBuilder vueProjectBuilder;

  @Override
  public Flux<String> chatToGenCode(Long appId, String userMessage, User loginUser) {
    // 参数校验
    ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "应用ID不能为空");
    ThrowUtils.throwIf(StringUtils.isBlank(userMessage), ErrorCode.PARAMS_ERROR, "用户提示词不能为空");
    // 查询应用是否存在
    App app = this.getById(appId);
    ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    // 权限校验，仅本人可以和自己的应用对话
    if (!app.getUserId().equals(loginUser.getId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }
    // 获取应用生成模式
    String codeGenType = app.getCodeGenType();
    CodeGenTypeEnum enumByValue = CodeGenTypeEnum.getEnumByValue(codeGenType);
    ThrowUtils.throwIf(enumByValue == null, ErrorCode.PARAMS_ERROR, "应用生成模式错误");

    //调用AI前保存用户消息到数据库中
    chatHistoryService.addChatMessage(appId, userMessage, ChatHistoryMessageTypeEnum.USER.getValue(), loginUser.getId());
    // 调用AI接口，生成代码
    Flux<String> codeStream = aiCodeGeneratorFacade.generateAndSaveCodeStream(userMessage, enumByValue, appId);
    // 收集AI响应的内容，完成后保存到对话历史
    StringBuilder aiResponseBuild = new StringBuilder();
    //针对不同的流，写不同的逻辑
    return streamHandlerExecutor.doExecute(codeStream,chatHistoryService,appId,loginUser, enumByValue);

//    return codeStream.map(chunk->{
//      // {"type": "ai_response"}
//      // 实时收集AI响应的内容
//      aiResponseBuild.append(chunk);
//      return chunk;
//    }).doOnComplete(()->{
//      // 返回完成后，保存AI消息到数据库
//      String aiResponse = aiResponseBuild.toString();
//      chatHistoryService.addChatMessage(appId, aiResponse, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
//
//    }).doOnError(error-> {
//      // 即使回复失败，也保存AI的消息
//      String errorMessage = "AI回复失败" +error.getMessage();
//      chatHistoryService.addChatMessage(appId, errorMessage, ChatHistoryMessageTypeEnum.AI.getValue(), loginUser.getId());
//    });
  }

  @Override
  public String deployApp(Long appId, User loginUser) {
    // 参数校验
    ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "应用ID不能为空");
    // 查询应用是否存在
    App app = this.getById(appId);
    ThrowUtils.throwIf(app == null, ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    // 权限校验，仅本人可以部署自己的应用
    ThrowUtils.throwIf(!app.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权限");
    // 检查是否已有deployKey，若没有则生成deployKey，六位，字母加数字
    String deployKey = app.getDeployKey();
    if (StringUtils.isBlank(deployKey)) {
      deployKey = UUID.randomUUID().toString().substring(0, 6);
    }
    // 获取原始代码生成路径（应用访问目录）
    String codeGenType = app.getCodeGenType();
    String sourceDirName = codeGenType + "_" + appId;
    String sourceDirPath = AppConstant.CODE_OUTPUT_ROOT_DIR + File.separator + sourceDirName;

    // 检查路径是否存在
    File sourceFile = new File(sourceDirPath);

    if (!sourceFile.exists() || !sourceFile.isDirectory()) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用代码不存在，请先生成应用");
    }

    // Vue项目特殊处理
    CodeGenTypeEnum enumByValue = CodeGenTypeEnum.getEnumByValue(codeGenType);
    if(enumByValue==CodeGenTypeEnum.VUE_PROJECT){
      boolean buildProject = vueProjectBuilder.buildProject(sourceDirPath);
      ThrowUtils.throwIf(!buildProject,ErrorCode.SYSTEM_ERROR,"VUE项目构建失败，请重试");
      // 检查dist目录是否存在
      File distFile = new File(sourceDirPath, "dist");
      ThrowUtils.throwIf(!distFile.exists(),ErrorCode.SYSTEM_ERROR,"项目路径不存在");
      sourceFile=distFile;
    }

    if (!sourceFile.exists() || !sourceFile.isDirectory()) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用代码不存在，请先生成应用");
    }



    // 移动文件到部署目录
    String deployDirPath = AppConstant.CODE_DEPLOY_ROOT_DIR + File.separator + deployKey;
    try {
      FileUtil.copyContent(sourceFile, new File(deployDirPath), true);
    } catch (Exception e) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "应用部署失败" + e.getMessage());
    }
    // 更新数据库
    App updateApp = new App();
    updateApp.setId(appId);
    updateApp.setDeployKey(deployKey);
    updateApp.setDeployedTime(LocalDateTime.now());
    updateApp.setUpdateTime(LocalDateTime.now());
    boolean updateById = this.updateById(updateApp);
    ThrowUtils.throwIf(!updateById, ErrorCode.OPERATION_ERROR, "应用部署失败");
    // 返回部署地址
    return String.format("%s/%s", AppConstant.CODE_DEPLOY_HOST, deployKey);
  }

  @Override
  public BaseResponse<Long> addApp(AppAddDTO appAddDTO, HttpServletRequest request) {
    if (appAddDTO == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }
    String initPrompt = appAddDTO.getInitPrompt();
    if (StringUtils.isBlank(initPrompt)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "初始化提示不能为空");
    }

    // 获取当前登录用户
    User loginUser = userService.getLoginUser(request);

    // 生成应用名称（基于提示词的前20个字符）
    String appName = generateAppName(initPrompt);

    // 创建应用
    App app = new App();
    app.setAppName(appName);
    app.setInitPrompt(initPrompt);
    app.setCodeGenType(CodeGenTypeEnum.VUE_PROJECT.getValue()); // 默认使用多文件模式
    app.setUserId(loginUser.getId());
    app.setCreateTime(LocalDateTime.now());
    app.setUpdateTime(LocalDateTime.now());

    boolean result = this.save(app);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建失败");

    return ResultUtils.success(app.getId());
  }

  @Override
  public BaseResponse<Boolean> updateApp(AppUpdateDTO appUpdateDTO, HttpServletRequest request) {
    if (appUpdateDTO == null || appUpdateDTO.getId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 获取当前登录用户
    User loginUser = userService.getLoginUser(request);

    // 查询应用是否存在且属于当前用户
    App oldApp = this.getById(appUpdateDTO.getId());
    if (oldApp == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }
    if (!oldApp.getUserId().equals(loginUser.getId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    // 更新应用
    App app = new App();
    app.setId(appUpdateDTO.getId());
    app.setAppName(appUpdateDTO.getAppName());
    app.setCover(appUpdateDTO.getCover());
    app.setUpdateTime(LocalDateTime.now());

    boolean result = this.updateById(app);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");

    return ResultUtils.success(true);
  }

  @Override
  public BaseResponse<Boolean> updateAppPublicStatus(AppPublicDTO appPublicDTO, HttpServletRequest request) {
    if (appPublicDTO == null || appPublicDTO.getAppId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }
    
    // 验证isPublic参数的有效性
    Integer isPublic = appPublicDTO.getIsPublic();
    if (isPublic == null || (isPublic != 0 && isPublic != 1)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "公开状态参数无效");
    }

    // 获取当前登录用户
    User loginUser = userService.getLoginUser(request);

    // 查询应用是否存在且属于当前用户
    App oldApp = this.getById(appPublicDTO.getAppId());
    if (oldApp == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }
    if (!oldApp.getUserId().equals(loginUser.getId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    // 更新应用公开状态
    App app = new App();
    app.setId(appPublicDTO.getAppId());
    app.setIsPublic(isPublic);
    app.setUpdateTime(LocalDateTime.now());

    boolean result = this.updateById(app);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");

    return ResultUtils.success(true);
  }

  @Override
  public BaseResponse<Boolean> deleteApp(DeleteRequest deleteRequest, HttpServletRequest request) {
    if (deleteRequest == null || deleteRequest.getId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 获取当前登录用户
    User loginUser = userService.getLoginUser(request);

    // 查询应用是否存在且属于当前用户
    App app = this.getById(deleteRequest.getId());
    if (app == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }
    if (!app.getUserId().equals(loginUser.getId())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    boolean result = this.removeById(deleteRequest.getId());
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");

    return ResultUtils.success(true);
  }

  @Override
  public BaseResponse<AppVO> getAppById(Long id, HttpServletRequest request) {
    if (id == null || id <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
    }

    App app = this.getById(id);
    if (app == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }

    AppVO appVO = getAppVO(app);
    return ResultUtils.success(appVO);
  }

  @Override
  public BaseResponse<Page<AppVO>> listMyAppByPage(AppQueryDTO appQueryDTO, HttpServletRequest request) {
    if (appQueryDTO == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 获取当前登录用户
    User loginUser = userService.getLoginUser(request);

    // 设置分页参数，每页最多20个
    int pageNum = appQueryDTO.getPageNum();
    int pageSize = Math.min(appQueryDTO.getPageSize(), AppConstant.MAX_PAGE_SIZE);

    // 构建查询条件
    QueryWrapper queryWrapper = QueryWrapper.create();
    queryWrapper.eq("userId", loginUser.getId());
    queryWrapper.eq("isDelete", 0);

    // 根据名称模糊查询
    if (StringUtils.isNotBlank(appQueryDTO.getAppName())) {
      queryWrapper.like("appName", appQueryDTO.getAppName());
    }

    // 按创建时间倒序
    queryWrapper.orderBy("createTime desc");

    // 分页查询
    Page<App> appPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);

    // 转换为VO，批量查询用户信息以优化性能
    List<AppVO> appVOList = getAppVOListWithUserInfo(appPage.getRecords());
    Page<AppVO> appVOPage = new Page<>(appPage.getPageNumber(), appPage.getPageSize(), appPage.getTotalRow());
    appVOPage.setRecords(appVOList);

    return ResultUtils.success(appVOPage);
  }

  @Override
  public BaseResponse<Page<AppVO>> listFeaturedAppByPage(AppQueryDTO appQueryDTO, HttpServletRequest request) {
    if (appQueryDTO == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 设置分页参数，每页最多20个
    int pageNum = appQueryDTO.getPageNum();
    int pageSize = Math.min(appQueryDTO.getPageSize(), AppConstant.MAX_PAGE_SIZE);

    // 构建查询条件
    QueryWrapper queryWrapper = QueryWrapper.create();
    queryWrapper.eq("isDelete", 0);
    queryWrapper.isNotNull("priority");
    queryWrapper.gt("priority", 0);

    // 根据名称模糊查询
    if (StringUtils.isNotBlank(appQueryDTO.getAppName())) {
      queryWrapper.like("appName", appQueryDTO.getAppName());
    }

    // 按优先级倒序，创建时间倒序
    queryWrapper.orderBy("priority desc, createTime desc");

    // 分页查询
    Page<App> appPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);

    // 转换为VO，批量查询用户信息以优化性能
    List<AppVO> appVOList = getAppVOListWithUserInfo(appPage.getRecords());
    Page<AppVO> appVOPage = new Page<>(appPage.getPageNumber(), appPage.getPageSize(), appPage.getTotalRow());
    appVOPage.setRecords(appVOList);

    return ResultUtils.success(appVOPage);
  }

  @Override
  public BaseResponse<Page<AppVO>> listAllFeaturedAppByPage(AppQueryDTO appQueryDTO) {
    if (appQueryDTO == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 设置分页参数，每页最多20个
    int pageNum = appQueryDTO.getPageNum();
    int pageSize = Math.min(appQueryDTO.getPageSize(), AppConstant.MAX_PAGE_SIZE);

    // 构建查询条件 - 查询所有精选应用（priority = 100）
    QueryWrapper queryWrapper = QueryWrapper.create();
    queryWrapper.eq("isDelete", 0);
    queryWrapper.eq("priority", AppConstant.FEATURED_PRIORITY);

    // 根据名称模糊查询
    if (StringUtils.isNotBlank(appQueryDTO.getAppName())) {
      queryWrapper.like("appName", appQueryDTO.getAppName());
    }

    // 按创建时间倒序
    queryWrapper.orderBy("createTime desc");

    // 分页查询
    Page<App> appPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);

    // 转换为VO，批量查询用户信息以优化性能
    List<AppVO> appVOList = getAppVOListWithUserInfo(appPage.getRecords());
    Page<AppVO> appVOPage = new Page<>(appPage.getPageNumber(), appPage.getPageSize(), appPage.getTotalRow());
    appVOPage.setRecords(appVOList);

    return ResultUtils.success(appVOPage);
  }

  @Override
  public BaseResponse<Page<AppVO>> listPublicAppByPage(AppQueryDTO appQueryDTO) {
    if (appQueryDTO == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 设置分页参数，每页最多20个
    int pageNum = appQueryDTO.getPageNum();
    int pageSize = Math.min(appQueryDTO.getPageSize(), AppConstant.MAX_PAGE_SIZE);

    // 构建查询条件 - 查询所有公开应用（isPublic = 1）
    QueryWrapper queryWrapper = QueryWrapper.create();
    queryWrapper.eq("isDelete", 0);
    queryWrapper.eq("isPublic", 1);

    // 根据名称模糊查询
    if (StringUtils.isNotBlank(appQueryDTO.getAppName())) {
      queryWrapper.like("appName", appQueryDTO.getAppName());
    }

    // 按创建时间倒序
    queryWrapper.orderBy("createTime desc");

    // 分页查询
    Page<App> appPage = this.page(new Page<>(pageNum, pageSize), queryWrapper);

    // 转换为VO，批量查询用户信息以优化性能
    List<AppVO> appVOList = getAppVOListWithUserInfo(appPage.getRecords());
    Page<AppVO> appVOPage = new Page<>(appPage.getPageNumber(), appPage.getPageSize(), appPage.getTotalRow());
    appVOPage.setRecords(appVOList);

    return ResultUtils.success(appVOPage);
  }

  @Override
  public BaseResponse<Boolean> deleteAppByAdmin(DeleteRequest deleteRequest, HttpServletRequest request) {
    if (deleteRequest == null || deleteRequest.getId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 验证管理员权限
    User loginUser = userService.getLoginUser(request);
    if (!UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    // 查询应用是否存在
    App app = this.getById(deleteRequest.getId());
    if (app == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }

    boolean result = this.removeById(deleteRequest.getId());
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");

    return ResultUtils.success(true);
  }

  @Override
  public BaseResponse<Boolean> updateAppByAdmin(AppUpdateAdminDTO appUpdateAdminDTO, HttpServletRequest request) {
    if (appUpdateAdminDTO == null || appUpdateAdminDTO.getId() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 验证管理员权限
    User loginUser = userService.getLoginUser(request);
    if (!UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    // 查询应用是否存在
    App oldApp = this.getById(appUpdateAdminDTO.getId());
    if (oldApp == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }

    // 更新应用
    App app = new App();
    app.setId(appUpdateAdminDTO.getId());
    app.setAppName(appUpdateAdminDTO.getAppName());
    app.setCover(appUpdateAdminDTO.getCover());
    app.setPriority(appUpdateAdminDTO.getPriority());
    app.setUpdateTime(LocalDateTime.now());

    boolean result = this.updateById(app);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");

    return ResultUtils.success(true);
  }

  @Override
  public BaseResponse<Page<AppVO>> listAppByPageByAdmin(AppQueryAdminDTO appQueryAdminDTO, HttpServletRequest request) {
    if (appQueryAdminDTO == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 验证管理员权限
    User loginUser = userService.getLoginUser(request);
    if (!UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    // 构建查询条件
    QueryWrapper queryWrapper = QueryWrapper.create();
    queryWrapper.eq("isDelete", 0);

    // 根据ID查询
    if (appQueryAdminDTO.getId() != null) {
      queryWrapper.eq("id", appQueryAdminDTO.getId());
    }

    // 根据名称模糊查询
    if (StringUtils.isNotBlank(appQueryAdminDTO.getAppName())) {
      queryWrapper.like("appName", appQueryAdminDTO.getAppName());
    }

    // 根据代码生成类型查询
    if (StringUtils.isNotBlank(appQueryAdminDTO.getCodeGenType())) {
      queryWrapper.eq("codeGenType", appQueryAdminDTO.getCodeGenType());
    }

    // 根据部署标识查询
    if (StringUtils.isNotBlank(appQueryAdminDTO.getDeployKey())) {
      queryWrapper.eq("deployKey", appQueryAdminDTO.getDeployKey());
    }

    // 根据优先级查询
    if (appQueryAdminDTO.getPriority() != null) {
      queryWrapper.eq("priority", appQueryAdminDTO.getPriority());
    }

    // 根据用户ID查询
    if (appQueryAdminDTO.getUserId() != null) {
      queryWrapper.eq("userId", appQueryAdminDTO.getUserId());
    }

    // 按创建时间倒序
    queryWrapper.orderBy("createTime desc");

    // 分页查询
    Page<App> appPage = this.page(new Page<>(appQueryAdminDTO.getPageNum(), appQueryAdminDTO.getPageSize()),
        queryWrapper);

    // 转换为VO，批量查询用户信息以优化性能
    List<AppVO> appVOList = getAppVOListWithUserInfo(appPage.getRecords());
    Page<AppVO> appVOPage = new Page<>(appPage.getPageNumber(), appPage.getPageSize(), appPage.getTotalRow());
    appVOPage.setRecords(appVOList);

    return ResultUtils.success(appVOPage);
  }

  @Override
  public BaseResponse<AppVO> getAppByIdByAdmin(Long id, HttpServletRequest request) {
    if (id == null || id <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
    }

    // 验证管理员权限
    User loginUser = userService.getLoginUser(request);
    if (!UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    App app = this.getById(id);
    if (app == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }

    AppVO appVO = getAppVO(app);
    return ResultUtils.success(appVO);
  }

  @Override
  public BaseResponse<Boolean> setAppFeature(AppFeatureDTO appFeatureDTO, HttpServletRequest request) {
    if (appFeatureDTO == null || appFeatureDTO.getId() == null || appFeatureDTO.getIsFeatured() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
    }

    // 验证管理员权限
    User loginUser = userService.getLoginUser(request);
    if (!UserConstant.ADMIN_ROLE.equals(loginUser.getUserRole())) {
      throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
    }

    // 查询应用是否存在
    App app = this.getById(appFeatureDTO.getId());
    if (app == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "应用不存在");
    }

    // 更新精选状态
    App updateApp = new App();
    updateApp.setId(appFeatureDTO.getId());
    // 如果精选，设置优先级为100，否则设置为0
    updateApp.setPriority(appFeatureDTO.getIsFeatured() ? AppConstant.FEATURED_PRIORITY : AppConstant.DEFAULT_PRIORITY);
    updateApp.setUpdateTime(LocalDateTime.now());

    boolean result = this.updateById(updateApp);
    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "设置精选状态失败");

    return ResultUtils.success(true);
  }

  /**
   * 对象转换
   */
  private AppVO getAppVO(App app) {
    if (app == null) {
      return null;
    }
    AppVO appVO = new AppVO();
    BeanUtils.copyProperties(app, appVO);

    // 查询并设置用户基础信息
    if (app.getUserId() != null) {
      User user = userService.getById(app.getUserId());
      if (user != null) {
        UserBasicVO userBasicVO = getUserBasicVO(user);
        appVO.setUser(userBasicVO);
      }
    }

    return appVO;
  }

  /**
   * 用户对象转换为用户基础信息VO
   */
  private UserBasicVO getUserBasicVO(User user) {
    if (user == null) {
      return null;
    }
    UserBasicVO userBasicVO = new UserBasicVO();
    userBasicVO.setId(user.getId());
    userBasicVO.setUserAccount(user.getUserAccount());
    userBasicVO.setUserName(user.getUserName());
    userBasicVO.setUserAvatar(user.getUserAvatar());
    userBasicVO.setUserProfile(user.getUserProfile());
    userBasicVO.setUserRole(user.getUserRole());
    userBasicVO.setEmail(user.getEmail());
    userBasicVO.setShareCode(user.getShareCode());
    userBasicVO.setCreateTime(user.getCreateTime());
    return userBasicVO;
  }

  /**
   * 根据提示词生成应用名称
   */
  private String generateAppName(String initPrompt) {
    if (StringUtils.isBlank(initPrompt)) {
      return AppConstant.DEFAULT_APP_NAME;
    }

    // 取提示词的前20个字符作为应用名称
    String appName = initPrompt.trim();
    if (appName.length() > AppConstant.MAX_APP_NAME_LENGTH) {
      appName = appName.substring(0, AppConstant.MAX_APP_NAME_LENGTH) + "...";
    }

    return appName;
  }

  /**
   * 批量转换应用列表，包含用户信息（优化性能）
   */
  private List<AppVO> getAppVOListWithUserInfo(List<App> appList) {
    if (appList == null || appList.isEmpty()) {
      return new ArrayList<>();
    }

    // 收集所有用户ID
    Set<Long> userIds = appList.stream()
        .map(App::getUserId)
        .filter(Objects::nonNull)
        .collect(Collectors.toSet());

    // 批量查询用户信息
    final Map<Long, User> userMap;
    if (!userIds.isEmpty()) {
      List<User> users = userService.listByIds(userIds);
      userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));
    } else {
      userMap = new HashMap<>();
    }

    // 转换应用列表
    return appList.stream().map(app -> {
      AppVO appVO = new AppVO();
      BeanUtils.copyProperties(app, appVO);

      // 设置用户信息
      if (app.getUserId() != null) {
        User user = userMap.get(app.getUserId());
        if (user != null) {
          appVO.setUser(getUserBasicVO(user));
        }
      }

      return appVO;
    }).collect(Collectors.toList());
  }

  /**
   * 删除应用时
   * @param
   * @return
   */
  @Override
  public boolean removeById(Serializable id) {
    if(id == null){
      return false;
    }
    Long appId = Long.valueOf(id.toString());
    if(appId == null || appId <= 0){
      return false;
    }
    // 先删除管理的对话历史
      try {
          chatHistoryService.deleteByAppId(appId);
      } catch (Exception e) {
          log.error("删除用户历史信息失败：{}",e.getMessage());
      }
      return super.removeById(id);
  }
}
